package com.hcb.app911;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.adapter.NavDrawerListAdapter;
import com.hcb.common.ActionEvent;
import com.hcb.constants.Constants;
import com.hcb.controller.ContactController;
import com.hcb.controller.CustomerController;
import com.hcb.dto.ContactsDTO;
import com.hcb.dto.CustomerDTO;
import com.hcb.dto.NavDrawerItem;
import com.hcb.fragment.AboutFragment;
import com.hcb.fragment.EmergencyContactsFragment;
import com.hcb.fragment.HomeFragment;
import com.hcb.fragment.MyDetailsFragment;
import com.hcb.fragment.SearchForResponder;
import com.hcb.fragment.UpdateAlertFragment;
import com.hcb.webservice.ServiceHandler;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private String[] navMenuTitles;
	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;

	ImageView activity_main_content_button_menu;
	String idCustomer;
//	private Button btnDetail;
	private  ImageView imgHome, imgDetail;
	public static Context c;
	@SuppressLint("SdCardPath")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		c = this;
		setImgDetail((ImageView) findViewById(R.id.imgDetail));
		setImgHome((ImageView) findViewById(R.id.imgHome));
		getImgHome().setOnClickListener(this);
		getImgDetail().setOnClickListener(this);
		// TelephonyManager tm = (TelephonyManager) this
		// .getSystemService(Context.TELEPHONY_SERVICE);

		Bundle data = getIntent().getExtras();
		if (data != null) {
			idCustomer = data.getString("id");
			CustomerDTO dto = new CustomerDTO();
			dto.setCustomer_id(idCustomer);
			new VerySlowTask(dto).execute();
			// getCustomerById cus = new getCustomerById(dto, this);
			// new Thread(cus).start();
		}

		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

		navDrawerItems = new ArrayList<NavDrawerItem>();
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], 0));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], 0));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], 0));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], 0));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], 0));
		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		if (savedInstanceState == null) {
			displayView(0);
		}
		activity_main_content_button_menu = (ImageView) findViewById(R.id.activity_main_content_button_menu);
		activity_main_content_button_menu.setOnClickListener(this);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		EmergencyContactsFragment fragment = new EmergencyContactsFragment();
		fragment.onActivityResult(requestCode, resultCode, data);
		UpdateAlertFragment fm = new UpdateAlertFragment();
		fm.onActivityResult(requestCode, resultCode, data);

	}

	// private class TaskUploadImage extends AsyncTask<Object, Void, Void> {
	//
	// @Override
	// protected Void doInBackground(Object... params) {
	// // String[] params = {api_secret_key, file_stream, upLoadServerUri,
	// // query, alert_id,file_extension};
	// // String[] arr = (String[]) params[0];
	// // String urlPath = arr[0];
	// // String pathImg = arr[1];
	// //
	// // int t = ImageUtils.getInstance().uploadFile(urlPath, pathImg);
	// // Log.i("<<Hung upload>>", String.valueOf(t));
	//
	// String path = "/storage/sdcard0/DCIM/Camera/IMG_20141221_182252.jpg";
	//
	//
	//
	// uploadFile(path);
	// // RestClient client = new RestClient(Constants.URL_SERVICE);
	// // client.AddParam("query", "fileTransfer");
	// // client.AddParam("alert_id", "99");
	// // client.AddParam("file_contents", path);
	// // client.AddParam("api_secret_key",
	// // "3832_2hd3hdiwyu34eyeuidhd_948");
	// // //Other parameters here
	// //
	// // try {
	// // client.Execute(RequestMethod.POST);
	// // } catch (Exception e) {}
	// //
	//
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	// // dialog.dismiss();
	// }
	//
	// }
	//
	// // example
	//
	// public int uploadFile(String sourceFileUri) {
	//
	// HttpURLConnection conn = null;
	// DataOutputStream dos = null;
	// String lineEnd = "\r\n";
	// String twoHyphens = "--";
	// String boundary = "*****";
	// int bytesRead, bytesAvailable, bufferSize;
	// byte[] buffer;
	// int maxBufferSize = 1 * 1024 * 1024;
	// File sourceFile = new File(sourceFileUri);
	//
	// if (!sourceFile.isFile()) {
	//
	// // use only selectedImagePath. because it contains whole path. no
	// // need to add /mnt/sdcard....
	// Log.e("uploadFile", "Source File not exist :" + selectedImagePath);
	//
	// // use only selectedImagePath. because it contains whole path. no
	// // need to add /mnt/sdcard....
	// runOnUiThread(new Runnable() {
	// public void run() {
	//
	// }
	// });
	//
	// return 0;
	// } else {
	// try {
	//
	// String path = "/storage/sdcard0/DCIM/Camera/IMG_20141221_182252.jpg";
	// String fileName = sourceFileUri;
	//
	// // open a URL connection to the Servlet
	// FileInputStream fileInputStream = new FileInputStream(
	// sourceFile);
	// URL url = new URL(Constants.URL_SERVICE);
	// System.out.println(url);
	// // Open a HTTP connection to the URL
	// conn = (HttpURLConnection) url.openConnection();
	// conn.setDoInput(true); // Allow Inputs
	// conn.setDoOutput(true); // Allow Outputs
	// conn.setUseCaches(false); // Don't use a Cached Copy
	//
	// // conn.setRequestMethod("POST");
	// conn.setRequestProperty("Connection", "Keep-Alive");
	// conn.setRequestProperty("ENCTYPE", "image/jpeg");
	// conn.setRequestProperty("Content-Type", "image/jpeg" + boundary);
	// conn.setRequestProperty("file_contents", fileName);
	//
	// List<NameValuePair> params = new ArrayList<NameValuePair>();
	// params.add(new BasicNameValuePair("query", "fileTransfer"));
	// params.add(new BasicNameValuePair("alert_id", "99"));
	// params.add(new BasicNameValuePair("file_contents", path));
	// params.add(new BasicNameValuePair("api_secret_key",
	// "3832_2hd3hdiwyu34eyeuidhd_948"));
	//
	// dos = new DataOutputStream(conn.getOutputStream());
	// BufferedWriter writer = new BufferedWriter(
	// new OutputStreamWriter(dos, "UTF-8"));
	// writer.write(getQuery(params));
	//
	// /*
	// * dos.writeBytes("version=apps"+"user_login_id=" + User_ID +
	// * "image_1="+imgs + "action="+btns); System.out.println(url);
	// */
	//
	// // dos = new DataOutputStream(conn.getOutputStream());
	//
	// dos.writeBytes(twoHyphens + boundary + lineEnd);
	// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
	// + fileName + "\"" + lineEnd);
	//
	// dos.writeBytes(lineEnd);
	//
	// /*
	// * JSONObject jsonParam = new JSONObject(); final String sta =
	// * jsonParam.getString("status"); Log.d("Stautus is", sta);
	// * final String msg = jsonParam.getString("msg");
	// * Log.d("Message is", msg);
	// */
	//
	// // create a buffer of maximum size
	// bytesAvailable = fileInputStream.available();
	//
	// bufferSize = Math.min(bytesAvailable, maxBufferSize);
	// buffer = new byte[bufferSize];
	//
	// // read file and write it into form...
	// bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	//
	// while (bytesRead > 0) {
	//
	// dos.write(buffer, 0, bufferSize);
	// bytesAvailable = fileInputStream.available();
	// bufferSize = Math.min(bytesAvailable, maxBufferSize);
	// bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	//
	// }
	//
	// // send multipart form data necesssary after file data...
	// dos.writeBytes(lineEnd);
	// dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	//
	// // Responses from the server (code and message)
	// int serverResponseCode = conn.getResponseCode();
	// String serverResponseMessage = conn.getResponseMessage();
	//
	// Log.i("uploadFile", "HTTP Response is : "
	// + serverResponseMessage + ": " + serverResponseCode);
	//
	// if (serverResponseCode == 200) {
	//
	// runOnUiThread(new Runnable() {
	// public void run() {
	//
	// /*
	// * String msg =
	// * "File Upload Completed.\n\n See uploaded file here : \n\n"
	// * +" http://www.androidexample.com/media/uploads/"
	// * +selectedImagePath;
	// *
	// * messageText.setText(msg);
	// */
	//
	// }
	// });
	// }
	//
	// // close the streams //
	// fileInputStream.close();
	// dos.flush();
	// dos.close();
	//
	// } catch (MalformedURLException ex) {
	//
	// ex.printStackTrace();
	//
	// runOnUiThread(new Runnable() {
	// public void run() {
	//
	// }
	// });
	//
	// Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
	// } catch (Exception e) {
	//
	// e.printStackTrace();
	//
	// runOnUiThread(new Runnable() {
	// public void run() {
	//
	// }
	// });
	// Log.e("Upload file to server Exception",
	// "Exception : " + e.getMessage(), e);
	// }
	//
	// return 1;
	//
	// } // End else block
	//
	// }
	//
	// private String getQuery(List<NameValuePair> params)
	// throws UnsupportedEncodingException {
	// StringBuilder result = new StringBuilder();
	// boolean first = true;
	//
	// for (NameValuePair pair : params) {
	// if (first)
	// first = false;
	// else
	// result.append("&");
	//
	// result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
	// result.append("=");
	// result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
	// }
	//
	// return result.toString();
	// }
	//
	// public class VerySlowTaskUpload extends AsyncTask<Void, Void, Void> {
	// String urlimg = "";
	// String path = "/storage/sdcard0/DCIM/Camera/IMG_20141221_182252.jpg";
	// public VerySlowTaskUpload(String _selectedImagePath) {
	// urlimg = _selectedImagePath;
	// }
	//
	// // String result;
	// // CustomerDTO customer;
	// //
	// // public VerySlowTask(CustomerDTO cus) {
	// // customer = cus;
	// // }
	//
	// @Override
	// protected Void doInBackground(Void... params) {
	//
	//
	// DefaultHttpClient httpclient = new DefaultHttpClient();
	// HttpPost postRequest = new HttpPost(Constants.URL_SERVICE);
	// try {
	// MultipartEntity reqEntity = new MultipartEntity();
	//
	// reqEntity.addPart("query", new StringBody("fileTransfer"));
	// reqEntity.addPart("alert_id", new StringBody("99"));
	//
	// reqEntity.addPart("file_contents", new FileBody(new File(path)));
	// reqEntity.addPart("api_secret_key", new StringBody(Constants.API_KEY));
	// postRequest.setEntity(reqEntity);
	//
	// HttpResponse response = httpclient.execute(postRequest);
	// String t = "";
	//
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// // ServiceHandler sh = new ServiceHandler();
	// // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	// // nameValuePairs.add(new BasicNameValuePair("query", "fileTransfer"));
	// //
	// // nameValuePairs.add(new BasicNameValuePair("alert_id", "99"));
	// //
	// // nameValuePairs.add(new BasicNameValuePair("file_contents", path));
	// // nameValuePairs.add(new BasicNameValuePair("api_secret_key",
	// // Constants.API_KEY));
	// //
	// // String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
	// // ServiceHandler.UPLOAD, nameValuePairs);
	// // if (jsonStr != null) {
	// // try {
	// // JSONObject object;
	// // object = new JSONObject(jsonStr);
	// // String value = object.getString("result");
	// // if (value.contains("success")) {
	// //
	// // // ActionEvent e = new ActionEvent(
	// // // MainActivity.this,
	// // // Constants.INSERT_CUSTOMER_EXIST, customer, null);
	// // // CustomerController.getInstance().handleViewEvent(e);
	// // }
	// // } catch (JSONException e) {
	// // e.printStackTrace();
	// // }
	// // } else {
	// // // Log.e("ServiceHandler",
	// // // "Couldn't get any data from the url");
	// // }
	//
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	// // TODO Auto-generated method stub
	// super.onPostExecute(result);
	//
	// }
	//
	// }
	//
	// public String getPath(Uri uri) {
	// String[] projection = { MediaStore.Images.Media.DATA };
	// Cursor cursor = managedQuery(uri, projection, null, null, null);
	// int column_index = cursor
	// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	// cursor.moveToFirst();
	// return cursor.getString(column_index);
	// }

	// end test
	/*
	 * private class SendHttpRequestTask extends AsyncTask<String, Void, String>
	 * {
	 * 
	 * @Override protected String doInBackground(String... params) { String url
	 * = params[0]; String param1 = params[1]; String param2 = params[2]; String
	 * param3 = params[3]; String param4 = params[4]; Bitmap b =
	 * BitmapFactory.decodeResource( MainActivity.this.getResources(),
	 * R.drawable.add); b = BitmapFactory.decodeFile(param3);
	 * 
	 * ByteArrayOutputStream baos = new ByteArrayOutputStream();
	 * b.compress(CompressFormat.PNG, 0, baos);
	 * 
	 * try { HttpClient client = new HttpClient(url);
	 * client.connectForMultipart(); client.addFormPart("fileTransfer", param1);
	 * client.addFormPart("alert_id", param2);
	 * client.addFilePart("file_contents", "", baos.toByteArray());
	 * client.addFormPart("api_secret_key", param4); client.finishMultipart();
	 * String data = client.getResponse(); int i = 0; } catch (Throwable t) {
	 * t.printStackTrace(); }
	 * 
	 * return null; }
	 * 
	 * @Override protected void onPostExecute(String data) { //
	 * item.setActionView(null);
	 * 
	 * }
	 * 
	 * }
	 */

	/*
	 * private class validation implements Runnable {
	 * 
	 * CustomerDTO customer; Context contextRunnable; String img = "";
	 * 
	 * public validation(CustomerDTO cus, Context context) { customer = cus;
	 * contextRunnable = context; }
	 * 
	 * public validation(String selectedImagePath, MainActivity context) { img =
	 * selectedImagePath; }
	 * 
	 * @Override public void run() { String url = Constants.URL_SERVICE1 +
	 * "fileTransfer"; url += "?query=" + "fileTransfer"; url += "?alert_id=" +
	 * "99"; url += "?file_contents=" + img; url += "?api_secret_key=" +
	 * "3832_2hd3hdiwyu34eyeuidhd_948"; String jsonResponse =
	 * WebService.getInstance().get(url); try { JSONObject object; object = new
	 * JSONObject(jsonResponse); String value = object.getString("result"); if
	 * (value.contains("success")) {
	 * 
	 * } } catch (JSONException e) { e.printStackTrace(); return; }
	 * 
	 * }
	 * 
	 * }
	 */
	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			displayView(position);
		}
	}

	private void displayView(int position) {
		// update the main content by replacing fragments
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new HomeFragment();
			break;
		case 1:
			fragment = new EmergencyContactsFragment();
			break;
		case 2:
			fragment = new MyDetailsFragment();
			break;
		case 3:
			fragment = new SearchForResponder();
			break;
		case 4:
			fragment = new AboutFragment();
			break;

		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();

			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
			
//			activity_main_content_button_menu.setImageResource(R.drawable.ic_drawer);
		} else {
			// error in creating fragment
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */
	public void onDrawerClosed(View view) {
		activity_main_content_button_menu.setImageResource(R.drawable.ic_drawer);
        // calling onPrepareOptionsMenu() to show action bar icons
        invalidateOptionsMenu();
    }

    public void onDrawerOpened(View drawerView) {
    	activity_main_content_button_menu.setImageResource(R.drawable.ic_drawerf);
        // calling onPrepareOptionsMenu() to hide action bar icons
        invalidateOptionsMenu();
    }
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		if(drawerOpen){
			activity_main_content_button_menu.setImageResource(R.drawable.ic_drawerf);
		}else{
			activity_main_content_button_menu.setImageResource(R.drawable.ic_drawer);
		}
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		// mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		// mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.activity_main_content_button_menu:
			if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
//				activity_main_content_button_menu.setImageResource(R.drawable.ic_drawer);
				mDrawerLayout.closeDrawer(mDrawerList);
			} else {
//				activity_main_content_button_menu.setImageResource(R.drawable.ic_drawerf);
				mDrawerLayout.openDrawer(mDrawerList);
			}
			break;
		case R.id.imgHome:
			HomeFragment fragment = new HomeFragment();
			FragmentManager fragmentManager = getSupportFragmentManager();
			FragmentTransaction ft = fragmentManager.beginTransaction();

			if (fragment != null) {
				ft.remove(fragment);
				ft.replace(R.id.frame_container, fragment);
				ft.commit();
			}
			break;

		case R.id.imgDetail:
			MyDetailsFragment mydetail = new MyDetailsFragment();
			FragmentManager fm = getSupportFragmentManager();
			FragmentTransaction trans = fm.beginTransaction();

			if (mydetail != null) {
				trans.remove(mydetail);
				trans.replace(R.id.frame_container, mydetail);
				trans.commit();
			}
			break;

		default:
			break;
		}

	}

	public ImageView getImgHome() {
		return imgHome;
	}

	public void setImgHome(ImageView imgHome) {
		this.imgHome = imgHome;
	}


	public ImageView getImgDetail() {
		return imgDetail;
	}

	public void setImgDetail(ImageView imgDetail) {
		this.imgDetail = imgDetail;
	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		String result;
		CustomerDTO customer;

		public VerySlowTask(CustomerDTO cus) {
			customer = cus;
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.GET_CUSTOMER_DETAILS));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));
			nameValuePairs.add(new BasicNameValuePair(Constants.CUSTOMER_ID,
					customer.getCustomer_id()));
			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject object;
					object = new JSONObject(jsonStr);
					JSONObject cus = object.getJSONObject("data_body");
					String value = object.getString("result");
					if (value.contains("success")) {
						customer.setName(cus.getString("name"));
						customer.setMobile_number(cus
								.getString("mobile_number"));
						customer.setEmail_address(cus
								.getString("email_address"));
						customer.setSex(cus.getString("sex"));
						customer.setAge(cus.getString("age"));
						ActionEvent e = new ActionEvent(MainActivity.this,
								Constants.INSERT_CUSTOMER_EXIST, customer, null);
						CustomerController.getInstance().handleViewEvent(e);

						ArrayList<ContactsDTO> arr = new ArrayList<ContactsDTO>();
						ContactsDTO contact = new ContactsDTO();
						String nominated_conact_name_one = cus
								.getString("nominated_conact_name_one");
						if (!nominated_conact_name_one.equalsIgnoreCase("")){
							contact.setName(nominated_conact_name_one);
							arr.add(contact);
						}
						String nominated_conact_number_one = cus
								.getString("nominated_conact_number_one");
							
						if (!nominated_conact_number_one.equalsIgnoreCase("")){
							contact.setNumber(nominated_conact_number_one);
							arr.add(contact);
						}
							
						
						if (arr.size() == 1) {
							ActionEvent e1 = new ActionEvent(MainActivity.this,
									Constants.INSERT_CONTACT_EXITS, contact, null);
							ContactController.getInstance().handleViewEvent(e1);
							
						}
						contact = new ContactsDTO();
						arr = new ArrayList<ContactsDTO>();
						String nominated_conact_name_two = cus
								.getString("nominated_conact_name_two");
						if (!nominated_conact_name_two.equalsIgnoreCase("")){
							contact.setName(nominated_conact_name_two);
							arr.add(contact);
						}
						
							
						String nominated_conact_number_two = cus
								.getString("nominated_conact_number_two");
						if (!nominated_conact_number_two.equalsIgnoreCase("")){
							contact.setNumber(nominated_conact_number_two);
							arr.add(contact);
						}
							
						
						if (arr.size() == 1) {
							ActionEvent e1 = new ActionEvent(MainActivity.this,
									Constants.INSERT_CONTACT_EXITS, contact, null);
							ContactController.getInstance().handleViewEvent(e1);
						}

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

		}

	}
	// private class getCustomerById implements Runnable {
	//
	// CustomerDTO customer;
	// Context contextRunnable;
	//
	// public getCustomerById(CustomerDTO cus, Context context) {
	// customer = cus;
	// contextRunnable = context;
	// }
	//
	// @Override
	// public void run() {
	// String url = Constants.URL_SERVICE
	// + "getCustomerIdWithVerificationCode";
	// url += "/api_secret_key/" + "3832_2hd3hdiwyu34eyeuidhd_948";
	// url += "/query/" + "getCustomerIdWithVerificationCode";
	// url += "/access_code/" + edAccessCode.getText().toString().trim();
	// String jsonResponse = WebService.getInstance().get(url);
	// try {
	// JSONObject object;
	// object = new JSONObject(jsonResponse);
	// String value = object.getString("result");
	// String idget = object.getString("data_body");
	// if (value.contains("success")) {
	// String urlget = Constants.URL_SERVICE
	// + "getCustomerIdWithVerificationCode";
	// urlget += "/api_secret_key/"
	// + "3832_2hd3hdiwyu34eyeuidhd_948";
	// urlget += "/query/" + "getCustomerDetails";
	// urlget += "/customer_id/"
	// + edAccessCode.getText().toString().trim();
	// String jsonget = WebService.getInstance().get(urlget);
	//
	// // ActionEvent e = new ActionEvent(ValidationActivity.this,
	// // Constants.UPDATE_CUSTOMER, customer, null);
	// // CustomerController.getInstance().handleViewEvent(e);
	//
	// Intent intent = new Intent(ValidationActivity.this,
	// MainActivity.class);
	//
	// Bundle bundle = new Bundle();
	// bundle.putString("id", idget);
	// intent.putExtras(bundle);
	// // Bundle bundle1 = new Bundle();
	// // bundle1.putSerializable("customer", customer);
	// // intent.putExtras(bundle1);
	// startActivity(intent);
	// finish();
	// }
	// } catch (JSONException e) {
	// e.printStackTrace();
	// return;
	// }
	//
	// }
	//
	// }

	// public void onClick(View v) {
	// int id = v.getId();
	//
	// switch (id) {
	// case R.id.activity_main_content_button_menu:
	// toggle();
	// break;
	//
	// default:
	// break;
	// }
	//
	// }
	//
	// public void switchContent(Fragment fragment) {
	// mContent = fragment;
	// FragmentManager fm = getSupportFragmentManager();
	// FragmentTransaction ft = fm.beginTransaction();
	//
	// if (fragment != null) {
	// ft.remove(fragment).replace(R.id.content_frame, fragment);
	// ft.commit();
	// }
	// getSlidingMenu().showContent();
	// }

}
